package com.example.mxh_location;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Address;
import android.os.Build;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.util.ArrayList;

import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.embedding.engine.plugins.activity.ActivityAware;
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
import io.flutter.plugin.common.EventChannel;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;

/** MxhLocationPlugin */
public class MxhLocationPlugin implements FlutterPlugin, MethodCallHandler, EventChannel.StreamHandler, ActivityAware {

  private MethodChannel channel;
  private EventChannel eventChannel;
  private EventChannel.EventSink eventSink;
  //  private ResultStateful resultStateful;
  private Result result;
  private Context context;
  private Activity activity;

//  public static void registerWith(Activity activity, BinaryMessenger messenger) {
//    MethodChannel channel = new MethodChannel(messenger, "asr_plugin");
//    MxhLocationPlugin instance = new MxhLocationPlugin();
//    channel.setMethodCallHandler(instance);
//  }

  @Override
  public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
    //可以利用flutterPluginBinding对象获取到Android中需要的Context对象
    context = flutterPluginBinding.getApplicationContext();
    //设置channel名称，之后flutter中也要一样
    channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "mxh_location");
    channel.setMethodCallHandler(this);

    eventChannel = new EventChannel(flutterPluginBinding.getBinaryMessenger(), "mxh_location_event");
    eventChannel.setStreamHandler(this);
  }

  @Override
  public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
    this.result = result;
    switch (call.method) {
      case "getPlatformVersion":
        result.success("Android " + android.os.Build.VERSION.RELEASE);
        break;
      case "startLocation":
        startLocation();
//        result.success("开始定位!!!");
        break;
      case "stopLocation":
        result.success("停止定位");
        break;
      case "testandroid":
        result.success("测试安卓");
        break;
      default:
        result.notImplemented();
    }
  }


  @Override
  public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
    channel.setMethodCallHandler(null);
  }

  void sendEventToStream(String data) {
    if (eventSink != null) {
      eventSink.success(data);
    }
  }

  @Override
  public void onListen(Object arguments, EventChannel.EventSink events) {
    //event 监听
    eventSink = events;
  }

  @Override
  public void onCancel(Object arguments) {
    eventSink = null;
  }

  private void startLocation() {
    initPermission();
    initLocation();
  }

  /**
   * 加载位置
   */
  private void initLocation() {
    LocationUtils.getInstance(activity).setAddressCallback(new LocationUtils.AddressCallback() {
      @Override
      public void onGetAddress(Address address) {
        String countryName = address.getCountryName();//国家
        String adminArea = address.getAdminArea();//省
        String locality = address.getLocality();//市
        String subLocality = address.getSubLocality();//区
        String featureName = address.getFeatureName();//街道
        Log.d("定位地址：", countryName + adminArea + locality + subLocality + featureName);
      }

      @Override
      public void onGetLocation(double lat, double lng) {
//        Log.d("经纬度", Double.toString(lat) + '#' + Double.toString(lng));
        String location = Double.toString(lat) + '-' + Double.toString(lng);
        sendEventToStream(location);
      }
    });
  }

  @Override
  public void onAttachedToActivity(@NonNull ActivityPluginBinding binding) {
    activity = binding.getActivity();
  }

  @Override
  public void onDetachedFromActivityForConfigChanges() {

  }

  @Override
  public void onReattachedToActivityForConfigChanges(@NonNull ActivityPluginBinding binding) {

  }

  @Override
  public void onDetachedFromActivity() {

  }

  /**
   * android 6.0 以上需要动态申请权限
   */
  private void initPermission() {
    String permissions[] = {
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_NETWORK_STATE
    };

    ArrayList<String> toApplyList = new ArrayList<String>();
    for (String perm : permissions) {
      if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(context, perm)) {
        toApplyList.add(perm);
        // 进入到这里代表没有权限.
      }
    }
    String tmpList[] = new String[toApplyList.size()];
    if (!toApplyList.isEmpty()) {
      ActivityCompat.requestPermissions(activity, toApplyList.toArray(tmpList), 123);
    }
  }



}